package com.bojiu.lawsearch.lawsearch.wxzf;

import com.bojiu.lawsearch.lawsearch.mapper.*;
import com.bojiu.lawsearch.lawsearch.model.*;
import com.bojiu.lawsearch.lawsearch.service.TaskService;
import com.bojiu.lawsearch.lawsearch.util.Constances;
import com.bojiu.lawsearch.lawsearch.util.UtilTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

/**
 * @author: afdiao
 * @Date：2020/4/9 23:50
 * @Description:处理微信返回的通知
 */
@Service
@Slf4j
public class PayResultHandler {

    @Autowired
    WxzfModelMapper wxzfModelMapper;

    @Autowired
    WechatUserMapper wechatUserMapper;

    @Autowired
    WxGoodsMapper wxGoodsMapper;

    @Autowired
    UserAccountMapper userAccountMapper;

    @Autowired
    LogMapper logMapper;

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    TaskService taskService;

    @Async
    public synchronized void handle(Map<String, String> map) {
        //首先判断是否统一处理
        String return_code = map.get("return_code");
        if (!"SUCCESS".equals(return_code)) {
            log.error("微信通知显示失败，map is ：{}", map);
            return;
        }
        //获取订单号
        String orderNum = map.get("out_trade_no");
        Wxzf_model wxzf_model = (Wxzf_model) wxzfModelMapper.selectOneByExample(UtilTools.createExampleByKey("orderNum", orderNum, Wxzf_model.class));
        log.debug("wxzf_model is :{}", wxzf_model.toString());
        if (wxzf_model.getHandle() != null) {
            if (wxzf_model.getHandle() == 1) {
                log.debug("该订单通知已经处理，orderNum is :{}", orderNum);
                return;
            }
        }
        String model = wxzf_model.getModel();
        switch (model) {
            case "member":
                //处理会员时间
                handelMember(wxzf_model);
                break;
            case "fee":
                //处理充值余额
                handleFee(wxzf_model);
                break;
            case "question":
                // 问答
                handleQuestion(wxzf_model);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + model);
        }
    }

    /**
     * 处理微信支付会员
     *
     * @param wxzf_model
     */
    private void handelMember(Wxzf_model wxzf_model) {
        Integer userId = wxzf_model.getUserId();
        Integer goodsId = wxzf_model.getGoodsId();
        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        WxGoods wxGoods = (WxGoods) wxGoodsMapper.selectOneByExample(UtilTools.createExampleByKey("id", goodsId, WxGoods.class));
        Integer time = wxGoods.getTime();
        String memberTime = wechatUser.getMemberTime();
        if (StringUtils.isEmpty(memberTime) || System.currentTimeMillis() / 1000 > Long.valueOf(memberTime)) {
            long newTime = System.currentTimeMillis() / 1000 + Long.valueOf(time * 3600);
            wechatUser.setMemberTime(String.valueOf(newTime));
            wechatUser.setGoodsId(goodsId);
            wechatUserMapper.updateByExampleSelective(wechatUser, UtilTools.createExampleByKey("id", userId, WechatUser.class));
        } else {
            //当前时间还是有效的，延长时间
            long newTime = Long.valueOf(memberTime) + Long.valueOf(time * 3600 * 24);
            wechatUser.setGoodsId(goodsId);
            wechatUser.setMemberTime(String.valueOf(newTime));
            wechatUserMapper.updateByExampleSelective(wechatUser, UtilTools.createExampleByKey("id", userId, WechatUser.class));
        }
        //更新此订单已经处理过了
        wxzf_model.setHandle(1);
        wxzfModelMapper.updateByExampleSelective(wxzf_model, UtilTools.createExampleByKey("orderNum", wxzf_model.getOrderNum(), Wxzf_model.class));
    }

    /**
     * 处理用户充值余额的通知
     *
     * @param wxzf_model
     */
    public void handleFee(Wxzf_model wxzf_model) {
        Integer userId = wxzf_model.getUserId();
        Integer price = wxzf_model.getPrice();
        WechatUser wechatUser = (WechatUser) wechatUserMapper.selectOneByExample(UtilTools.createExampleByKey("id", userId, WechatUser.class));
        int before = 0;
        int after = 0;
        if (userAccountMapper.selectCountByExample(UtilTools.createExampleByKey("user_id", userId, UserAccount.class)) == 0) {
            after = price;
            UserAccount userAccount = new UserAccount();
            userAccount.setUser_id(userId);
            userAccount.setAccount(price);
            userAccount.setIntegral(0);
            userAccountMapper.insertSelective(userAccount);
        } else {
            UserAccount userAccount = (UserAccount) userAccountMapper.selectOneByExample(UtilTools.createExampleByKey("user_id", userId, UserAccount.class));
            before = userAccount.getAccount();
            Integer account = userAccount.getAccount();
            account = account + price;
            userAccount.setAccount(account);
            after = account;
            userAccountMapper.updateByExampleSelective(userAccount, UtilTools.createExampleByKey("user_id", userId, UserAccount.class));
        }

        //历史记录
        Log scoreLog = new Log();
        scoreLog.setType(2);
        scoreLog.setUserId(userId);
        scoreLog.setBefore(String.valueOf(before));
        scoreLog.setValue(String.valueOf(price));
        scoreLog.setAfter(String.valueOf(after));
        scoreLog.setDetail(Constances.LOG_FEE_TYPE);
        logMapper.insertSelective(scoreLog);

        //更新此订单已经处理过了
        wxzf_model.setHandle(1);
        wxzfModelMapper.updateByExampleSelective(wxzf_model, UtilTools.createExampleByKey("orderNum", wxzf_model.getOrderNum(), Wxzf_model.class));

        //TODO:处理下家
    }

    public void handleQuestion(Wxzf_model wxzf_model) {
        String orderNum = wxzf_model.getOrderNum();
        Task task = (Task) taskMapper.selectOneByExample(UtilTools.createExampleByKey("orderNum", orderNum, Task.class));
        taskService.publishByStatus(task.getId());
        //更新此订单已经处理过了
        wxzf_model.setHandle(1);
        wxzfModelMapper.updateByExampleSelective(wxzf_model, UtilTools.createExampleByKey("orderNum", wxzf_model.getOrderNum(), Wxzf_model.class));

        //历史记录
        Log scoreLog = new Log();
        scoreLog.setType(2);
        scoreLog.setUserId(task.getUserId());
        scoreLog.setValue(String.valueOf(task.getPrice() * 100));
        scoreLog.setDetail(Constances.LOG_QUESTION_TYPE);
        logMapper.insertSelective(scoreLog);
    }
}
